package com.yneusoft.manage.service;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yneusoft.common.model.ResponseWrapper;
import com.yneusoft.common.tool.CommonTool;
import com.yneusoft.dao.entity.Book;
import com.yneusoft.dao.entity.BookType;
import com.yneusoft.dao.mapper.BookMapper;
import com.yneusoft.dao.mapper.BookTypeMapper;
import com.yneusoft.manage.mapper.BookManageMapper;
import com.yneusoft.manage.model.*;
import com.yneusoft.manage.model.param.*;
import com.yneusoft.manage.model.result.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * @author wb
 * @date 2021/10/20 19:05
 * @description: 图书管理模块 业务实现
 */
@Service
public class BookManageService {

    @Autowired
    private BookMapper bookMapper;


    @Autowired
    private BookTypeMapper bookTypeMapper;

    @Autowired
    private BookManageMapper bookManageMapper;


    /**
     * 1.获取图书类型
     *
     * @return aid 图书aid，name 图书类型名称
     */
    public ResponseWrapper getBookType() {
        LambdaQueryWrapper<BookType> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByAsc(BookType::getAid);
        List<Map<String, Object>> mapList = bookTypeMapper.selectMaps(wrapper);
        List<BookTypeListItemModel> results = CommonTool.mapListToBeanList(mapList, BookTypeListItemModel.class);
        return ResponseWrapper.markSuccess(results);
    }

    /**
     * 2.获取图书列表
     *
     * @param param GetBookListParam类
     * @return rowNumber 总记录数，totalNumber 图书总数，aid 图书aid，isbn isbn号，typeName 图书类型名称，name 图书名，quantity 图书数量，createTime  新增日期
     */
    public ResponseWrapper getBookList(SearchBookParam param) {
        Integer page = param.getPage();
        Integer pageSize = param.getPageSize();
        Integer typeAid = param.getTypeAid();
        String searchKey = param.getSearchKey();
        int current = (page - 1) * pageSize;
        if(StringUtils.isNotBlank(param.getSearchKey())){
            param.setSearchKey("%"+param.getSearchKey()+"%");
        }
        String bookName = param.getSearchKey();
        List<Map<String, Object>> bookList = bookManageMapper.getBookList(bookName, typeAid, current, pageSize);
        List<BookListItemModel> listResults = CommonTool.mapListToBeanList(bookList, BookListItemModel.class);
        Map<String, Object> rowNumberAndTotalNumber = bookManageMapper.getRowNumberAndTotalNumber(bookName, typeAid);
        GetBookListResult result = new GetBookListResult();
        result.setRowNumber(Integer.parseInt(rowNumberAndTotalNumber.get("rowNumber").toString()));
        if(rowNumberAndTotalNumber.get("totalNumber")!=null){
            result.setTotalNumber(Integer.parseInt(rowNumberAndTotalNumber.get("totalNumber").toString()));
        }
        else{
            result.setTotalNumber(0);
        }
        result.setList(listResults);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 3.根据id删除图书
     *
     * @param param DeleteBookParam
     */
    @Transactional
    public ResponseWrapper delBook(DeleteBookParam param) {
        try {
            bookMapper.deleteById(param.getAid());
            return ResponseWrapper.markSuccess();
        } catch (Exception e) {
            e.fillInStackTrace();
            return ResponseWrapper.markError();
        }
    }

    /**
     * 4.校验损坏数量
     *
     * @param param CheckDamageBookQuantityParam类
     * @return isExist true：超额，false:未超额
     */

    public ResponseWrapper checkDamageBook(CheckDamageBookQuantityParam param) {
        try {
            Integer damageQuantity = param.getDemageQuantity();
            Book book = bookMapper.selectById(param.getAid());
            Integer quantity = book.getQuantity();
            CheckDamageQuantityResult checkDamageQuantityResult = new CheckDamageQuantityResult();
            checkDamageQuantityResult.setIsExcess(damageQuantity > quantity);
            return ResponseWrapper.markSuccess(checkDamageQuantityResult);
        } catch (Exception e) {
            return ResponseWrapper.markError();
        }
    }

    /**
     * 5.损坏图书(获取图书数量后，更新图书信息)
     *
     * @param param DamageBookCommitParam类
     * @return ResponseWrapper更新的结果
     */
    @Transactional
    public ResponseWrapper damageBook(DemageBookParam param) {
        try {
            Book book = bookMapper.selectById(param.getAid());
            Integer demageQuantity = param.getDemageQuantity();
            Integer currentQuantity = book.getQuantity() - demageQuantity;
            LambdaUpdateWrapper<Book> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper
                    .eq(Book::getAid,param.getAid())
                    .set(Book::getQuantity,currentQuantity)
                    .set(param.getRemarks()!=null,Book::getRemarks,param.getRemarks());
            bookMapper.update(null,updateWrapper);
            return ResponseWrapper.markSuccess();
        } catch (Exception e) {
            return ResponseWrapper.markError();
        }
    }

    /**
     * 6.获取图书信息
     *
     * @param aid 图书aid
     * @return getBookInfoResult
     */
    public ResponseWrapper getBookInfo(Integer aid) {
        Map<String, Object> bookInfo = bookManageMapper.getBookinfo(aid);
        GetBookInfoResult result = BeanUtil.toBean(bookInfo,GetBookInfoResult.class);
        return ResponseWrapper.markSuccess(result);
    }

    /**
     * 7、【新增/修改】获取图书类型
     *
     * @return ResponseWrapper
     */
    public ResponseWrapper getAllType() {
        List<Map<String, Object>> mapList = bookTypeMapper.selectMaps(null);
        List<BookTypeModel> typeList = CommonTool.mapListToBeanList(mapList, BookTypeModel.class);
        Map<String, Object> map ;
        List<Map<String, Object>> result = new ArrayList<>();
        for (BookTypeModel item : typeList) {
            if (item.getFatherAid() == null) {
                map = new HashMap<>();
                map.put("aid", item.getAid());
                map.put("name", item.getName());
                this.getChildrenTree(map, typeList);
                result.add(map);
            }
        }
        List<BookTypeTreeNodeModel> listResults = CommonTool.mapListToBeanList(result, BookTypeTreeNodeModel.class);
        return ResponseWrapper.markSuccess(listResults);
    }

    /**
     * 8.校验ISBN
     *
     * @param param CheckIsbnParam类中的ISBN编号
     * @return isbnResult
     */
    public ResponseWrapper checkIsbn(CheckISBNParam param) {
        String isbn = param.getIsbn();
        Integer aid = param.getAid();
        Map<String, Object> book = bookManageMapper.checkBookIsbn(isbn,aid);
        CheckBookIsbnResult checkBookIsbnResult = new CheckBookIsbnResult();
        if (book != null){
            GetBookInfoResult getBookInfoResult = BeanUtil.toBean(book,GetBookInfoResult.class);
            checkBookIsbnResult.setIsExist(true);
            checkBookIsbnResult.setBookInfo(getBookInfoResult);
            return ResponseWrapper.markSuccess(checkBookIsbnResult);
        }else {
            checkBookIsbnResult.setIsExist(false);
            return ResponseWrapper.markSuccess(checkBookIsbnResult);
        }
    }

    /**
     * 9.新增/修改图书信息
     *
     * @param param SaveBookParam类
     * @author: lt
     * @date: 2021/10/24 16:58
     */
    @Transactional
    public ResponseWrapper saveBook(SaveBookParam param) {
        Book book = new Book();
        book.setName(param.getName());
        book.setIsbn(param.getIsbn());
        book.setQuantity(param.getQuantity());
        book.setTypeAid(param.getTypeAid());
        if (param.getRemarks() != null) book.setRemarks(param.getRemarks());
        LambdaUpdateWrapper<Book> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(param.getRemarks() == null, Book::getRemarks, null);
        try {
            if (param.getAid() == -1) {
                bookMapper.insert(book);
            } else {
                updateWrapper.eq(Book::getAid, param.getAid());
                bookMapper.update(book, updateWrapper);
            }
            return ResponseWrapper.markSuccess();
        } catch (Exception e) {
            return ResponseWrapper.markError();
        }
    }


    private void getChildrenTree(Map<String, Object> map, List<BookTypeModel> list) {
        List<Map<String, Object>> sonList = new ArrayList<>();
        Map<String, Object> childrenMap;
        for (BookTypeModel item : list) {
            if (map.get("aid") == item.getFatherAid()) {
                childrenMap = new HashMap<>();
                childrenMap.put("aid", item.getAid());
                childrenMap.put("name", item.getName());
                sonList.add(childrenMap);
                this.getChildrenTree(childrenMap, list);
            }
        }
        map.put("children", sonList);
    }
}
















